﻿using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RuoYi.Model.ResponseModel;
using RuoYi.Model.ToolModel;

namespace RuoYi.Admin.Controllers.Api
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        /// <summary>
        /// 返回操作结果对象
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        protected InfoModel OpReturn(int result, string msg = "", string massage = "")
        {
            InfoModel infoModel = new InfoModel();

            if (result > 0)
            {
                infoModel.Info = result;
                infoModel.Code = ResultEnum.Success;
                infoModel.Msg = massage == "" ? msg + "成功" : massage;
            }
            else
            {
                infoModel.Info = result;
                infoModel.Code = ResultEnum.Fail;
                infoModel.Msg = massage == "" ? msg + "失败" : massage;
            }
            return infoModel;
        }

        /// <summary>
        /// 返回数据对象
        /// </summary>
        /// <param name="result"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        protected InfoModel DataReturn(object result, string msg)
        {
            InfoModel infoModel = new InfoModel();

            if (result != null)
            {
                infoModel.Info = result;
                infoModel.Code = ResultEnum.Success;
                infoModel.Msg = msg;
            }
            else
            {
                infoModel.Info = result;
                infoModel.Code = ResultEnum.Fail;
                infoModel.Msg = msg;
            }
            return infoModel;
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="bytes">字节流</param>
        /// <param name="fileName">文件名,包含扩展名</param>
        /// <param name="encoding">字符编码</param>
        protected async Task DownloadAsync(byte[] bytes, string fileName, Encoding encoding)
        {
            if (bytes == null || bytes.Length == 0)
                return;
            fileName = fileName.Replace(" ", "");
            fileName = HttpUtility.UrlEncode(fileName, encoding);
            HttpContext.Response.ContentType = "application/octet-stream";
            HttpContext.Response.Headers.Add("Content-Disposition", $"attachment; filename={fileName}");
            HttpContext.Response.Headers.Add("Content-Length", bytes.Length.ToString());
            await Response.Body.WriteAsync(bytes, 0, bytes.Length);
        }
    }
}
